import ajax from './ajax'

const _processDownload = function(res, filename) {
  let link = document.createElement('a');
  let url = window.URL.createObjectURL(res.data);
  link.href = url;
  link.download = filename;
  link.click();
  setTimeout(function(){
    try {
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    }  catch(e) {}
  }, 100);
}

// status: -2被删除;-1被拉黑;0正常;1等回应;2待联系

export default {

    saveAuthor(author, onSuccess, onError) {
        ajax.post('/douban/authors', author)
          .then(onSuccess)
          .catch(onError);
    },

    importAuthor(file, onSuccess, onError) {
      let fd = new FormData();
      fd.append('file', file);
      ajax.post('/douban/authors/excel', fd, {headers:{'Content-Type':'multipart/form-data'}})
          .then(onSuccess).catch(onError);
    },
  
    queryAuthor(params, onSuccess, onError) {
      ajax.post('/douban/authors/query', params)
          .then(onSuccess)
          .catch(onError);
    },

    downloadAuthor(params, onComplete) {
      ajax({
        url:'/douban/authors/download',
        method:'POST',
        data: params,
        responseType:'blob'
      }).then(res=>{
        _processDownload(res, 'Douban-Author-' + new Date().getTime() + '.xlsx');
        onComplete();
      }).catch(onComplete);
    }
  }